import json
from MQTT import *
class com:
    '网络通讯模块'
    def __init__(self, name:str, ip:str, port:int, keepalive:int):
        '参数:车牌号、MQTT服务器IP地址、MQTT服务器端口'
        self.name = name # 设置车牌号
        self.mqtt = MQTT(ip, port, keepalive) # 创建MQTT实例
        self.topic =  '/traffic/car/' + name # 设定自己所在的频道
        
    def sent(self, x_position:int, y_position:int, facing:int, next_step:str, emergency:bool):
        '参数：X坐标、Y坐标、方向、下步操作、是否紧急'
        # nextstep指令有：
        #    左转：turn_left；右转：turn_right；
        # emergency情况有：
        #    紧急停车
        data = {'name':self.name, 'position': [x_position, y_position], 'facing': facing, 'next_step': next_step, 'emergency': emergency}

        data = json.dumps(data)
        data = data.encode(encoding='utf-8')
        self.mqtt.push(self.topic, data)
        return
    def receive(self):
        '调用方法：value = obj.receive()'
        
        data = self.rs.recv(4096)
        data = data.decode('utf-8')
        return data
